package com.exposit.zbs.controller;

import com.exposit.zbs.model.*;
import com.exposit.zbs.service.IGrantApplicationService;
import com.exposit.zbs.service.IMoneyTransferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/money")
public class MoneyTransferController {

	@Autowired
	private IMoneyTransferService moneyService;

	@Autowired
	private IGrantApplicationService gaService;

	@RequestMapping(value = "/grant/{grantId}", method = {RequestMethod.POST})
	public ModelAndView add(HttpSession session, @PathVariable String grantId, @PathVariable("grantId") GrantApplication grantApplication, Long moneyAmount) {  //TODO Validate fields!!!!!
		User user = (User) session.getAttribute("sessionUser");
		ModelAndView mav = new ModelAndView();
		if (user != null) {
			MoneyTransfer moneyTransfer = new MoneyTransfer();
			moneyTransfer.setUser(user);
			moneyTransfer.setMoneySum(moneyAmount);
			moneyTransfer.setGrantApplication(grantApplication);
			moneyTransfer.setDate(new java.util.Date());
			moneyService.saveMoney(moneyTransfer);
			mav = new ModelAndView("redirect:/grant/view/{grantId}");
			mav.addObject("message", "You have sent money successfully.");
			return mav;
		} else {

			mav.addObject("error", "You should be logged in");
			mav.setViewName("login");
			return mav;
		}
	}

	@RequestMapping(value = "/transfer", method = {RequestMethod.POST})
	@ResponseBody
	public GrantApplication transferMoney(@RequestBody GrantApplication grantApplication, HttpSession session) {

		return grantApplication;
	}

	@RequestMapping(value = "/grantArea/{grantAreaLink}", method = {RequestMethod.POST})
	public ModelAndView addAreaMoney(HttpSession session, @PathVariable String grantAreaLink, @PathVariable("grantAreaLink") GrantArea grantArea, Long moneyAmount) {  //TODO Validate fields!!!!!
		User user = (User) session.getAttribute("sessionUser");
		ModelAndView mav = new ModelAndView();
		if (user != null) {
			GrantAreaMoney moneyTransfer = new GrantAreaMoney();
			moneyTransfer.setUser(user);
			moneyTransfer.setMoneyAmount(moneyAmount);
			moneyTransfer.setGrantArea(grantArea);
			moneyTransfer.setDate(new java.util.Date());
			gaService.saveAreaMoneyTransfer(moneyTransfer);
			mav = new ModelAndView("redirect:/area/" + grantArea.getLink());
			mav.addObject("message", "You have sent money successfully.");
			return mav;
		} else {

			mav.addObject("error", "You should be logged in");
			mav.setViewName("login");
			return mav;
		}
	}
}

